﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ConcurrentProgram
{
    public class AsyncApp
    {
        #region 异步请求超时的代码
        /// <summary>
        /// 请求超时函数（指数退避）一共请求6次 第二次请求间隔1秒，第三次请求间隔2秒，4秒，8秒，16秒
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> DownloadStringWithReTries(string url)
        {
            using (var client = new HttpClient())
            {
                var nextDely = TimeSpan.FromSeconds(1);
                for (int i = 0; i < 5; i++)
                {
                    try
                    {
                        return await client.GetStringAsync(url);
                    }
                    catch (Exception ex)
                    {
                        //打个日志
                    }
                    await Task.Delay(nextDely);
                    nextDely += nextDely;
                }
                await Task.Delay(nextDely);
                return await client.GetStringAsync(url);
            }
        }




        /// <summary>
        /// 发送一个请求，三秒请求超时，返回请方法结果。
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> DownloadStringWithTimeout(string url)
        {
            using (var client = new HttpClient())
            {
                var downloadTask = client.GetStringAsync(url);
                var timeoutTask = Task.Delay(3000);
                var completedTask = await Task.WhenAny(downloadTask, timeoutTask);
                if (completedTask == timeoutTask)
                {
                    return null;
                }
                return await downloadTask;
            }
        }
        #endregion



    }
}
